import { login, logout, getInfo,getCompany } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import qs from 'querystring'
import jwt_decode from "jwt-decode"

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userId: '',
  userObj: {},
  companyList: [],
  // 0:正常；1:断电；2:离线；3:未知异常
  deviceClass: [
    {value:0, name:'正常'},
    {value:1, name:'断电'},
    {value:2, name:'离线'},
    {value:3, name:'未知异常'},
  ],
  // 0:测试设备；1:运营设备；2:预投放设备；3:体验设备；4:停用设备；5:其他用途
  deviceUse: [
    {value:0, name:'测试设备'},
    {value:1, name:'运营设备'},
    {value:2, name:'预投放设备'},
    {value:3, name:'体验设备'},
    {value:4, name:'停用设备'},
    {value:5, name:'其他用途'},
  ],
  //  0:快消品；1:生鲜；2:乳制品；目前只会有快消品
  goodBigClass: [
    {value:0, name:'快消品'},
    {value:1, name:'生鲜'},
    {value:2, name:'乳制品'}
  ],  
  //  0:罐；1:盒；2:瓶；3:桶；4:袋
  goodBox: [
    {value:0, name:'罐'},
    {value:1, name:'盒'},
    {value:2, name:'瓶'},
    {value:3, name:'桶'},
    {value:4, name:'袋'},
  ],    
  // 上下货工单状态：0:待分配；1:已分配；2:处理中；3:已完成；4:异常
  TicketStatus:[
    {value:0, name:'待分配'},
    {value:1, name:'已分配'},
    {value:2, name:'处理中'},
    {value:3, name:'已完成'},
    {value:4, name:'异常'},
  ],
  sourceList:[
    {value:0, name:'微信支付分支付'},
    {value:1, name:'支付宝免密支付'},
  ],
  orderStatus:[
    {value:0, name:'已创建'},
    {value:1, name:'正在检查订单'},
    {value:2, name:'订单信息已确认'},
    {value:3, name:'支付中'},
    {value:4, name:'已支付'},
    {value:5, name:'退款中'},
    {value:6, name:'退款成功'},
    {value:7, name:'系统补扣中'},
    {value:8, name:'补扣失败'},
    {value:9, name:'支付失败'},
    {value:10, name:'退款失败'},
    {value:11, name:'已取消'},
    {value:12, name:'异常状态'},
  ],
  orderCancleStatus:[
    {value:0, name:'取消订单'},
    {value:1, name:'支付宝免密支付'},
  ],
  // [Description("已创建")]
  //       Created = 0,
        
  //       [Description("正在检查订单")]
  //       Checking = 1,
        
  //       [Description("订单信息已确认")]
  //       Checked = 2,
        
  //       [Description("支付中")]
  //       Paying = 3,
        
  //       [Description("已支付")]
  //       Paid = 4,
        
  //       [Description("退款中")]
  //       Repaying = 5,
        
  //       [Description("退款成功")]
  //       Repaid = 6,
        
  //       [Description("系统补扣中")]
  //       Deductioning = 7,
        
  //       [Description("补扣失败")]
  //       DeductionFailed = 8,
        
  //       [Description("支付失败")]
  //       PaymentFailed = 9,
        
  //       [Description("退款失败")]
  //       RepayFailed = 10,
        
  //       [Description("已取消")]
  //       Cancelled = 11,
        
  //       [Description("异常状态")]
  //       Unknown = 12,
}

const mutations = {
  Authorization: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      var list = { client_id: "saas",client_secret: "saas_secret",grant_type: "password",username: username.trim(), password: password };
      list = qs.stringify(list);
      login(list).then(response => {
        const decode = jwt_decode(response.access_token);
        console.log(decode)
        // commit('SET_TOKEN', response.token_type + " " + response.access_token)
        commit('Authorization', response.token_type + " " + response.access_token)
        setToken(response.token_type + " " + response.access_token)
        state.userId = decode.user_id;
        localStorage.setItem('user_id', JSON.stringify(decode.user_id));
        getCompany(state.userId).then((res)=>{
          console.log(res)
          localStorage.setItem('companyList', JSON.stringify(res.result.authorizedTenants));
          localStorage.setItem('user_account', res.result.account);
        })
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getCompany(state.userId).then((res)=>{
        console.log(res)
        res.result.authorizedTenants;
      })
      getInfo(state.userId).then(response => {
        state.userObj = response.result;
        // const { data } = response

        // // if (!data) {
        // //   reject('Verification failed, please Login again.')
        // // }

        // const { roles, name, avatar, introduction } = data

        // // roles must be a non-empty array
        // if (!roles || roles.length <= 0) {
        //   reject('getInfo: roles must be a non-null array!')
        // }

        commit('SET_ROLES', ["admin"])
        commit('SET_NAME', response.result.name)
        commit('SET_AVATAR', "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif")
        commit('SET_INTRODUCTION', "I am a super administrator")
        resolve(response.result)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('Authorization', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('Authorization', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('Authorization', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
